﻿using System.Linq;
using System.Windows;
using Loki.UI;

namespace Luna.UI.Wpf
{
    /// <summary>
    /// Logique d'interaction pour MainTiles.xaml
    /// </summary>
    public partial class MainTiles : Loki.UI.Wpf.ViewWindow<MainViewModel>
    {
        public MainTiles()
        {
            InitializeComponent();
            DataContextChanged += MainTiles_DataContextChanged;
            FRM_Navigation.Navigated += FRM_Navigation_Navigated;
        }

        private void FRM_Navigation_Navigated(object sender, DevExpress.Xpf.WindowsUI.Navigation.NavigationEventArgs e)
        {
            var L_CurrentView = FRM_Navigation.Journal.Current.Source as IView;
            if (ViewModel != null && L_CurrentView == null)
            {
                ViewModel.Documents.Desactivate.Execute(null);
            }
        }

        private void MainTiles_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            if (ViewModel != null)
            {
                ViewModel.SubModelActivated += ViewModel_SubModelActivated;
                if (ViewModel.Documents != null)
                {
                    ViewModel.Documents.SubModels.CollectionChanged += SubModels_CollectionChanged;
                }
            }
        }

        private void PNL_Search_MouseLeave(object sender, System.Windows.Input.MouseEventArgs e)
        {
            if (ViewModel != null)
            {
                ViewModel.SearchActive = false;
            }
        }

        private void SubModels_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
        {
            if (ViewModel != null && ViewModel.Documents != null && ViewModel.Documents.SubModels.Count() == 0)
            {
                FRM_Navigation.Journal.GoHome();
            }
        }

        private void ViewModel_SubModelActivated(object sender, Loki.UI.ViewModelEventArgs e)
        {
            if (e.ViewModel != null && ViewModel != null)
            {
                var L_CurrentView = FRM_Navigation.Journal.Current.Source as IView;
                if (L_CurrentView == null || L_CurrentView.ViewModel != e.ViewModel)
                {
                    var L_View = Loki.Utils.ToolKit.Templates.GetView(e.ViewModel);
                    FRM_Navigation.Navigate(L_View);
                }

                //else
                //{
                //    FRM_Navigation.Journal.GoHome();
                //}
            }
        }
    }
}